﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php

using System.Web.Mail;
using System.Web;
using System.IO;

namespace DNA.Mvc.Notification
{
    public class TemplatedEmailSubscriptionSender : MailSubscriptionSender
    {
        /// <summary>
        /// Gets/Sets the template filename or virtual filename.
        /// </summary>
        public string Template { get; set; }

        protected override void OnPopuplateMailMessage(System.Net.Mail.MailMessage message)
        {
            if (!string.IsNullOrEmpty(Template))
            {
                var filename = Template;
                if (filename.StartsWith("~/"))
                    filename = HttpContext.Current.Server.MapPath(filename);
                if (File.Exists(filename))
                {
                    using (var reader = new StreamReader(filename))
                    {
                        string formatted = reader.ReadToEnd();
                        if (!string.IsNullOrEmpty(formatted))
                        {
                            formatted = formatted.Replace("[body]", message.Body);
                            formatted = formatted.Replace("[title]", message.Subject);
                            message.Body = formatted;
                        }
                    }
                }
            }
        }
    }
}
